package com.ewuyong.concurrence.example.syncContainer;

import com.ewuyong.concurrence.annotations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;


@Slf4j
public class VectorExample3 {


    public static List<Integer> vector1 = new ArrayList<>();

    public static void main(String[] args) throws InterruptedException {

        Vector<Integer> vector = new Vector<>();
        vector.add(1);
        vector.add(2);
        vector.add(3);
        vector.add(4);

        //test3(vector);
        test1(vector);
        //test2(vector);
        log.info("vector", vector.toArray());

    }

    private static void test3(Vector<Integer> vector ) {
        for (Integer i : vector) {
            if (i.equals(2)) {
                vector.remove(i);  //java.util.ConcurrentModificationException
            }
        }
    }

    private static void test1(Vector<Integer> vector ) {
        Iterator<Integer> iterator = vector.iterator();
        while (iterator.hasNext()){
            if (iterator.next().equals(2)){
                vector.remove(2);  //java.util.ConcurrentModificationException
            }
        }

    }

    private static void test2(Vector<Integer> vector ) {

        for (int i = 0; i < vector.size(); i++) {
            if (i ==2) {
                vector.remove(i);
            }
        }
    }
}
